﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MvcEngine.Core.Utils;
using System.Security.Principal;
using System.Web;
using MvcEngine.Core.Helpers;
using MvcEngine.Core.Repositories;
using MvcEngine.Core.Account;

namespace MvcEngine.Core
{
    public class UserContext : IUserContext
    {
        protected readonly string userSessionKey = "user";

        public UserContext()
        {

        }

        public static IUserContext Current
        {
            get { return IoC.Resolve<IUserContext>(); }
        }

        #region IUserContext Members

        public virtual User User
        {
            get
            {
                if (!IsLoggedIn)
                {
                    //User is not set yet, we return null.
                    return null;
                }

                string userName = GetCurrentUserIdentity().Name;
                if (string.IsNullOrEmpty(userName))
                    return null;

                if (!HttpSessionHelper.IsEmpty(userName, userSessionKey))
                    return HttpSessionHelper.GetValue<User>(userName, userSessionKey);
                //We have a logged in user but it cannot be found in the session, if this is the case the
                //session might be expired or the user was logged in by using cookies.
                //If that's the case we need to refetch the account and refill the user.

                User user = AccountManager.Current.GetUser(userName);
#warning Check why session is null
                if (HttpContext.Current.Session != null)
                {
                    HttpSessionHelper.SetValue<User>(userName, userSessionKey, user);
                }
                return user;
            }
        }

        public bool IsLoggedIn
        {
            get
            {
                IIdentity userIdentity = GetCurrentUserIdentity();
                return (userIdentity != null && userIdentity.IsAuthenticated);
            }
        }

        protected virtual IIdentity GetCurrentUserIdentity()
        {
            if (HttpContext.Current.User == null)
                return null;
            return HttpContext.Current.User.Identity;
        }

        #endregion

    }
}
